package com.llg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llg.mapper.SupplyBrandMapper;
import com.llg.model.code.CommonCode;
import com.llg.model.code.PageCode;
import com.llg.model.response.*;
import com.llg.pojo.SupplyBrand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class SupplyBrandService {

    @Autowired
    private SupplyBrandMapper supplyBrandMapper;

    //查询所有电源品牌列表
    public PageResult<SupplyBrand> findAll() {
        return new PageResult<>(CommonCode.SUCCESS, 1, 1, supplyBrandMapper.selectAll());
    }

    //搜索并分页查询
    public PageResult<SupplyBrand> findList(int currentPage, int pageSize, SupplyBrand supplyBrand) {
        //判断参数是否合法
        if (currentPage <= 0) return new PageResult<>(PageCode.PAGE_ERR1, 0, 0, null);
        if (pageSize <= 0) return new PageResult<>(PageCode.SIZE_ERR, 0, 0, null);
        PageHelper.startPage(currentPage, pageSize);
        Example example = new Example(SupplyBrand.class);
        Example.Criteria criteria = example.createCriteria();
        if (supplyBrand != null) {
            if (supplyBrand.getName() != null && !supplyBrand.getName().equals("")) {
                criteria.andLike("name", "%" + supplyBrand.getName() + "%");
            }

        }
        List<SupplyBrand> supplyBrands = supplyBrandMapper.selectByExample(example);
        PageInfo<SupplyBrand> page = new PageInfo<>(supplyBrands);
        return new PageResult<>(CommonCode.SUCCESS, (int)page.getTotal(),  page.getPages(), page.getList());
    }

    //通过查询
    public DataResult<SupplyBrand> findById(int id) {
        return new DataResult<>(CommonCode.SUCCESS, supplyBrandMapper.selectByPrimaryKey(id));
    }

    //增
    public DataResult<SupplyBrand> add(SupplyBrand supplyBrand) {
        supplyBrandMapper.insertSelective(supplyBrand);
        return new DataResult<>(CommonCode.SUCCESS, supplyBrand);
    }

    //删
    public ResponseResult delete(int id) {
        supplyBrandMapper.deleteByPrimaryKey(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //改
    public ResponseResult update(SupplyBrand supplyBrand) {
        supplyBrandMapper.updateByPrimaryKeySelective(supplyBrand);
        return new ResponseResult(CommonCode.SUCCESS);
    }
}
